from fastapi import Depends
from fastapi_amis_admin.globals.deps import SyncSess
from sqlalchemy import text
from superstream import Stream

from backend.apps.common import PageResult, CommonUtil
from backend.apps.menu.models import *
from backend.apps.security.models import SecurityUser

class MenuService:
    def page(params: MenuQueryParams, sess: SyncSess) -> PageResult:
        stmt = text('''
                    SELECT b.field_value as name,
                    a.id,
                    a.pid,
                    a.top_menu_id,
                    a.app_code,
                    a.url,
                    a.permissions,
                    a.type,
                    a.icon,
                    a.sort
                    FROM sys_menu a LEFT JOIN sys_language b on a.id=b.table_id
                    where b.field_value like :name 
                    ''').bindparams(name='yy')
        result = sess.execute(stmt).all()
        list = CommonUtil.list_tuple_to_model(result, SysMenuDTO)


        offset = (params.page - 1) * params.size
        sql_where = []
        if params and params.name:
            sql_where.append(SysMenu.username.contains(params.name))
        query = sess.query(SysMenu).where(*sql_where)
        results = query.offset(offset).limit(params.size).all()
        total = query.count()
        return PageResult(page=params.page, size=params.size, total=total, list=results)

    def list(sess: SyncSess):
        stmt = text('''
            SELECT b.field_value as name,
            a.id,
            a.pid,
            a.top_menu_id,
            a.app_code,
            a.url,
            a.permissions,
            a.type,
            a.icon,
            a.sort
            FROM sys_menu a LEFT JOIN sys_language b on a.id=b.table_id
            where b.field_value like :name
            ''').bindparams(name='yy')
        result = sess.execute(stmt).all()
        list = CommonUtil.list_tuple_to_model(result, SysMenuDTO)
        return list

    def detail(id: int, sess: SyncSess) -> SysMenu:
        obj = sess.get(SysMenu, id)
        return obj

    def save(sess: SyncSess, data: SysMenuDTO):
        menu = SysMenu(**dict(data))
        sess.add(menu)
        sess.commit()
        language = SysLanguage(table_name="sys_menu", table_id=menu.id, field_name="name", field_value=data.name, language="zh-CN")
        sess.add(language)

    def update(data: SysMenu, sess: SyncSess):
        print(dict(data))
        sess.query(SysMenu).filter(SysMenu.id == data.id).update(dict(data))

    def delete(id: int, sess: SyncSess):
        sess.query(SysMenu).filter(SysMenu.id == id).delete()